import { lazyReportBatch } from "../report";

export default function observerLCP() {
  const entryHandler = (list) => {
    //只处理一次LCP事件，避免重复观察
    if (observer) {
      observer.disconnect();
    }
    for (const entry of list.getEntries()) {
      const json = entry.toJSON();
      const reportData = {
        ...json,
        type: "performance",
        subType: entry.name,
        page: window.location.href,
      };
      // TODO: 发送数据
      lazyReportBatch(reportData);
    }
  };

  //统计和计算lcp的时间
  const observer = new PerformanceObserver(entryHandler);
  //buffered: true 确保观察到所有lcp事件
  observer.observe({ type: "largest-contentful-paint", buffered: true });
}
